<?php
namespace app\admin\controller;

use app\admin\model\AdminUser as AdminUserModel;
use app\admin\model\AuthGroup as AuthGroupModel;
use app\admin\model\AuthGroupAccess as AuthGroupAccessModel;
use app\admin\AdminBase;
use app\Request;
use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Db;
use think\facade\Session;
use think\facade\Validate;

/**
 * 管理员管理
 * Class AdminUser
 * @package app\admin\controller
 */
class AdminUser extends AdminBase
{
    protected $admin_user_model;
    protected $auth_group_model;
    protected $auth_group_access_model;

    protected function initialize()
    {
        parent::initialize();
        $this->admin_user_model        = new AdminUserModel();
        $this->auth_group_model        = new AuthGroupModel();
        $this->auth_group_access_model = new AuthGroupAccessModel();
    }

    /**
     * 管理员管理
     * @return mixed
     */
    public function index($keyword='',$page=1,$limit=15)
    {
      //  var_dump($this->request->isAjax());exit;
        if ($this->request->isAjax()) {


            $where = [];
            if($keyword){
                $where[] = ["username", "like", "%{$keyword}%"];
            }

            $admin_user_list = $this->admin_user_model ->order('id','desc')->paginate($limit);

           return $this->layui_json($admin_user_list->items(),$admin_user_list->total());
        }


        return $this->fetch('index');
    }
    /**
     * 修改密码
     * @return mixed
     */
    public function userpassword(){
        $id = session("admin_id");
        $admin_user  = $this->admin_user_model->find($id);
        return $this->fetch('userpassword', ['admin_user' => $admin_user]);
    }
    /**
     * 保存修改密码
     * @return mixed
     */
    public function updatePassword(){
        if ($this->request->isPost()) {
            $admin_id    = Session::get('admin_id');
            $data   = $this->request->param();
            $result = Db::name('admin_user')->find($admin_id);

            if ($result['password'] == md5($data['old_password'] . Config::get('app.salt'))) {
                if ($data['password'] == $data['confirm_password']) {
                    $new_password = md5($data['password'] . Config::get('app.salt'));
                    $res          = Db::name('admin_user')->where(['id' => $admin_id])->update(['password'=>$new_password]);
                    if ($res !== false) {
                        $this->success('修改成功');
                    } else {
                        $this->error('修改失败');
                    }
                } else {
                    $this->error('两次密码输入不一致');
                }
            } else {
                $this->error('原密码不正确');
            }
        }
    }
    /**
     * 添加管理员
     * @return mixed
     */
    public function create()
    {
        $auth_group_list = $this->auth_group_model->select();

        return $this->fetch('create', ['auth_group_list' => $auth_group_list]);
    }

    /**
     * 保存管理员
     * @param $group_id
     */
    public function save($group_id)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->param();
            try {

                validate(\app\admin\validate\AdminUser::class)->check($data);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                $this->error($e->getError());
            }
                $data['password'] = md5($data['password'] . Config::get('app.salt'));
                if ($this->admin_user_model->save($data)) {
                    $auth_group_access['uid']      = $this->admin_user_model->id;
                    $auth_group_access['group_id'] = $group_id;
                    $this->auth_group_access_model->save($auth_group_access);
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }

        }
    }

    /**
     * 编辑管理员
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $admin_user             = $this->admin_user_model->find($id);
        $auth_group_list        = $this->auth_group_model->select();
        $auth_group_access      = $this->auth_group_access_model->where('uid', $id)->find();
        $admin_user['group_id'] = $auth_group_access['group_id'];

        return $this->fetch('edit', ['admin_user' => $admin_user, 'auth_group_list' => $auth_group_list]);
    }

    /**
     * 更新管理员
     * @param $id
     * @param $group_id
     */
    public function update($id, $group_id)
    {
        if ($this->request->isPut()) {
            $data            = $this->request->put();
            $rule = [
                'username'         => 'require|unique:admin_user,id,'.$id,
                'password'         => 'confirm:confirm_password',
                'confirm_password' => 'confirm:password',
                'status'           => 'require',
                'group_id'         => 'require'
            ];
            $msg = [
                'username.require'         => '请输入用户名',
                'username.unique'          => '用户名已存在',
                'password.confirm'         => '两次输入密码不一致',
                'confirm_password.confirm' => '两次输入密码不一致',
                'status.require'           => '请选择状态',
                'group_id.require'         => '请选择所属权限组'
            ];
            $validate = Validate::rule($rule);
            $validate->message($msg);
            $result = $validate->check($data);
            if (!$result) {

                $this->error($validate->getError());
            } else {
                $admin_user = $this->admin_user_model->find($id);

                $admin_user->id       = $id;
                $admin_user->username = $data['username'];
                $admin_user->status   = $data['status'];

                if (!empty($data['password']) && !empty($data['confirm_password'])) {
                    $admin_user->password = md5($data['password'] . Config::get('app.salt'));
                }
                $admin_user->update_time = date("Y-m-d H:i:s");
                if ($admin_user->save() !== false) {
                    $auth_group_access['uid']      = $id;
                    $auth_group_access['group_id'] = $group_id;
                    $this->auth_group_access_model->where('uid', $id)->update($auth_group_access);
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }

    /**
     * 删除管理员
     * @param $id
     */
    public function delete($id)
    {
        if ($id == 1) {
            $this->error('默认管理员不可删除');
        }
        if ($this->admin_user_model->destroy($id)) {
            $this->auth_group_access_model->where('uid', $id)->delete();
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}